#!/usr/bin/env python3

from glob import glob
import json
import os
import sys

def log(message):
    sys.stderr.write(message + "\n")

def main():
    # Print Python version information
    print("Python version:")
    print("  " + sys.version.replace("\n", "\n  ").strip())
    print()

    # Print Linux distro information
    if os.path.exists("/etc/os-release"):
        with open("/etc/os-release", "r") as os_release:
            print("Content of /etc/os-release:")
            print("  " + os_release.read().replace("\n", "\n  ").strip())
    else:
        print("Couldn't find /etc/os-release")
    print()

    # Print the list of installed packages
    script_dir = os.path.dirname(os.path.realpath(__file__))
    orchestra_share = os.path.join(script_dir, "..", "share", "orchestra")

    if os.path.isdir(orchestra_share):
        print("Installed components:")
        for json_path in sorted(glob(os.path.join(orchestra_share, "*.json"))):
            try:
                with open(json_path, "r") as json_file:
                    print("  " + json.load(json_file)["binary_archive_path"])
            except:
                name = os.path.basename(json_path)
                print("  Couldn't extract `binary_archive_path` from " + name)
    else:
        print("share/orchestra does not exist")
    print()

    # Print revng-distributable information
    config_json_path = os.path.join(script_dir, "..", "..", "config.json")
    success = False
    if os.path.exists(config_json_path):
        try:
            with open(config_json_path, "r") as config_json:
                config = json.load(config_json)
                print("revng-distributable info:")
                print("  last-archive: " + config["last-archive"])
                print("  branch: " + config["branch"])
                success = True
        except:
            pass

    if not success:
        print("Couldn't get revng-distributable release info")

    return 0

if __name__ == "__main__":
    sys.exit(main())
